package com.nl.lib_project.view

import android.animation.AnimatorSet
import android.animation.ValueAnimator
import android.content.Context
import android.graphics.*
import android.util.AttributeSet
import android.view.View
import com.nl.lib_core.tool.extends.getColorResources
import com.nl.lib_project.R
import com.nl.lib_project.datas.LocalDbAutism

/**
 * 作者: wangfei 创建时间: 2021/10/8 包名: com.nl.lib_project.view 类名: CircularProgress
 *
 * <com.nl.lib_project.view.CircularProgress android:id="@+id/cp_status_01"
 * android:layout_width="0dp" android:layout_height="0dp" app:layout_constraintWidth_percent="0.15"
 * app:layout_constraintDimensionRatio="1:1" app:layout_constraintBottom_toBottomOf="parent"
 * app:layout_constraintEnd_toEndOf="parent" app:layout_constraintHorizontal_bias="0.3"
 * app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toTopOf="parent"
 * app:layout_constraintVertical_bias="0.2" />
 */
class CircularProgress : View {

  private var mTxtBgBitmap: Bitmap =
      BitmapFactory.decodeResource(resources, R.drawable.project_circular_progress_txt_bg)
  /** 指定图片绘制区域 */
  private val mTxtBgRect: Rect = Rect()
  /** 指定图片在屏幕上显示的区域 */
  private val mTxtBgDst: Rect = Rect()
  /** 实现颜色的过度渐变 */
  private val mGradient: SweepGradient by lazy {
    SweepGradient(
        measuredWidth / 2f,
        measuredHeight / 2f,
        intArrayOf(Color.argb(255, 10, 150, 250), Color.argb(255, 10, 221, 250)),
        floatArrayOf(0.3f, 0.7f))
  }
  /** 当前的进度 */
  private var mProgress: Float = 0f
  /** 当前数值 */
  private var mNumberText: String = "0"
  /** 当前总分 */
  private var mScoreText: String = "0"
  /** 当前结果标题 */
  private var mScoreTitle: String? = null
  /** 宽高 */
  private var mWidthSize = 0
  private var mHeightSize = 0
  /** 设置进度条大小 */
  private val mProgressRectF = RectF()
  /** 设置进度条背景 */
  private val mProgressBGPaint = Paint()
  /** 进度条走动的值 */
  private var mProgressPaint = Paint()
  /** 设置进度值画笔 */
  private var mTextPaint = Paint()
  /** 设置总分值画笔 */
  private var mScorePaint = Paint()
  /** 得分结果动画 */
  private val animatorSet by lazy { AnimatorSet() }
  /** 渐变色矩阵 */
  private val mMatrix by lazy { Matrix() }

  constructor(context: Context?) : super(context) {
    init()
  }

  constructor(context: Context?, attrs: AttributeSet?) : super(context, attrs) {
    init()
  }

  constructor(
      context: Context?,
      attrs: AttributeSet?,
      defStyleAttr: Int
  ) : super(context, attrs, defStyleAttr) {
    init()
  }

  private fun init() {
    mProgressPaint.apply {
      strokeWidth = 30f
      style = Paint.Style.STROKE
      strokeCap = Paint.Cap.ROUND
      isAntiAlias = true
    }
    mProgressBGPaint.apply {
      strokeWidth = 30f
      style = Paint.Style.STROKE
      strokeCap = Paint.Cap.ROUND
      isAntiAlias = true
      color = Color.argb(255, 240, 245, 250)
    }
    mTextPaint.apply {
      strokeWidth = 3f
      color = context.getColorResources(R.color.project_main_color)
      style = Paint.Style.FILL
      textSize = 40f
      isAntiAlias = true
      flags = Paint.ANTI_ALIAS_FLAG
      isFakeBoldText = true
      textAlign = Paint.Align.CENTER
    }
    mScorePaint.apply {
      strokeWidth = 3f
      color = context.getColorResources(R.color.colorPrimaryDark)
      style = Paint.Style.FILL
      textSize = 25f
      flags = Paint.ANTI_ALIAS_FLAG
      isFakeBoldText = true
      textAlign = Paint.Align.CENTER
    }
  }

  override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
    super.onMeasure(widthMeasureSpec, heightMeasureSpec)
    mWidthSize = MeasureSpec.getSize(widthMeasureSpec)
    mHeightSize = MeasureSpec.getSize(heightMeasureSpec)
    setMeasuredDimension(mWidthSize, mHeightSize)
  }
  var flag = false
  override fun onDraw(canvas: Canvas) {
    super.onDraw(canvas)
    canvas.save()
    // 旋转画布绘制小箭头的得分图片
    canvas.rotate(158f + mProgress, width / 2f, height / 2f)
    // 设置画布范围
    mTxtBgRect.set(0, 0, mTxtBgBitmap.width, mTxtBgBitmap.height)
    // 绘制带箭头的图片
    mTxtBgDst.set(46, 46, mWidthSize - 44, mHeightSize - 44)
    // 绘制文字的背景色
    canvas.drawBitmap(mTxtBgBitmap, mTxtBgRect, mTxtBgDst, null)
    // 恢复旋转
    canvas.restore()
    // 设置渐变色
    if (mGradient.getLocalMatrix(mMatrix).not()) {
      mGradient.setLocalMatrix(
          mMatrix.apply { postRotate(120f, measuredWidth / 2f, measuredHeight / 2f) })
      mProgressPaint.shader = mGradient
      flag = true
    }
    mProgressRectF.set(15f, 15f, mWidthSize - 15f, mHeightSize - 15f)
    canvas.drawArc(mProgressRectF, 135f, 270f, false, mProgressBGPaint)
    // 绘制圆弧，第三个参数，是从第二个参数的角度算起
    canvas.drawArc(mProgressRectF, 135f, mProgress, false, mProgressPaint)
    // 绘制得分
    val numberTextWidth = mTextPaint.measureText(mNumberText)
    val numberPositionX = (measuredWidth - numberTextWidth) / 2f
    val positionY = mHeightSize / 2f + 10f
    canvas.drawText(mNumberText, numberPositionX, positionY, mTextPaint)
    // 绘制总分
    val scoreTextWidth = mScorePaint.measureText(mScoreText)
    val scorePositionX = (measuredWidth + scoreTextWidth) / 2f
    canvas.drawText(mScoreText, scorePositionX, positionY, mScorePaint)
    //    // 标题
    //    mScoreTitle?.let {
    //      canvas.drawText(it, measuredWidth / 2f, measuredHeight / 2f + 35f, mScorePaint)
    //    }
  }

  /** 设置进度 */
  fun setProgress(
      progressValue: Double,
      scoreText: String,
      totalScoreText: String,
      scoreTitle: String?
  ) {
    // 最终旋转弧度
    val mTargetProgress = (progressValue * 270).toFloat()
    mScoreText = "/$totalScoreText"
    mScoreTitle = scoreTitle ?: context.getString(R.string.circular_progress_score)
    handlerProgressAnimation(mTargetProgress, scoreText)
  }

  /** 处理进度条动画 */
  private fun handlerProgressAnimation(progress: Float, text: String) {
    val progressAnimator = ValueAnimator.ofFloat(0f, progress)
    progressAnimator.addUpdateListener {
      mProgress = it.animatedValue as Float
      postInvalidate(left, top, right, bottom)
    }
    val textAnimator = ValueAnimator.ofInt(0, text.toInt())
    textAnimator.addUpdateListener { mNumberText = it.animatedValue.toString() }
    animatorSet.duration = LocalDbAutism.VIEW_SCROLL_DURATION_1000L
    animatorSet.playTogether(progressAnimator, textAnimator)
    animatorSet.start()
  }

  /** 回收动画 */
  override fun onDetachedFromWindow() {
    super.onDetachedFromWindow()
    animatorSet.end()
  }
}
